/**
 * 
 */
package com.effectivsocial.service.impl;


import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import com.effectivsocial.domain.Company;
import com.effectivsocial.domain.NetworkType;
import com.effectivsocial.domain.SocialNetwork;
import com.effectivsocial.domain.User;
import com.effectivsocial.repository.LovRepository;
import com.effectivsocial.repository.SocialNetworkRepository;
import com.effectivsocial.repository.UserRepository;
import com.effectivsocial.service.api.AbstractService;
import com.effectivsocial.service.api.SocialNetworkService;

/**
 * @author Dhrubo
 *
 */
@Transactional(readOnly=true)
@Named
@Slf4j
public class SocialNetworkServiceImpl extends AbstractService<SocialNetwork, String>
		implements SocialNetworkService {
	
	@Inject
	private SocialNetworkRepository repository;
	
	@Inject
	private UserRepository userRepository;
	
	@Inject
	private LovRepository lovRepository;
	
	@Override
	protected void initInternal() {
		setRepository(repository);		
	}
	
	
	public List<SocialNetwork> findByLoggedInUser(Pageable pageable) {
        
        User user = getLoggedInUser();
        
        log.info("Logged in user = {}", user);
        
        return repository.findByUsers(pageable, user);        
	}

	
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void save(SocialNetwork network) {
		
		log.info("Saving new network = {}", network);
		
		User user = userRepository.findOne(getLoggedInUser().getId());
		List<User> users = new ArrayList<User>();
		users.add(user);
		network.setUsers(users);
		
		Company company = user.getCompany();
		network.setCompany(company);
		
		network.setSharedSecret(UUID.randomUUID().toString());
		
		NetworkType type = (NetworkType) lovRepository.findByTypeAndName(network.getNetworkType().getType(), network.getNetworkType().getName());
		network.setNetworkType(type);
		
		includeAuditForSave(network);
		
		repository.save(network);

	}

	@Transactional(readOnly=true)
	public SocialNetwork findBySharedSecret(String apiKey) {
		SocialNetwork network = repository.findBySharedSecret(apiKey);
		if(network != null) {
			log.info("Found network, fetching owners.");
			network.getUsers();
		}
		return network;
	}

}
